package luren.king.wechatlite.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import luren.king.wechatlite.R;
import luren.king.wechatlite.pojo.ChatMessage;

public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<ChatMessage> mChatMessageList;

    public ChatAdapter(List<ChatMessage> chatMessageList) {
        mChatMessageList = chatMessageList;
    }

    @Override
    public int getItemViewType(int position) {
        ChatMessage message = mChatMessageList.get(position);
        return message.getType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == ChatMessage.TYPE_SENT) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_chat_sent, parent, false);
            return new SentMessageHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_chat_received, parent, false);
            return new ReceivedMessageHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ChatMessage message = mChatMessageList.get(position);
        if (holder instanceof SentMessageHolder) {
            ((SentMessageHolder) holder).bind(message);
        } else {
            ((ReceivedMessageHolder) holder).bind(message);
        }
    }

    @Override
    public int getItemCount() {
        return mChatMessageList.size();
    }

    private static class SentMessageHolder extends RecyclerView.ViewHolder {
        private TextView messageText;

        public SentMessageHolder(View itemView) {
            super(itemView);
            messageText = itemView.findViewById(R.id.text_message_sent);
        }

        public void bind(ChatMessage message) {
            messageText.setText(message.getContent());
        }
    }

    private static class ReceivedMessageHolder extends RecyclerView.ViewHolder {
        private TextView messageText;

        public ReceivedMessageHolder(View itemView) {
            super(itemView);
            messageText = itemView.findViewById(R.id.text_message_received);
        }

        public void bind(ChatMessage message) {
            messageText.setText(message.getContent());
        }
    }
}

